//
//  ViewController.m
//  XWXWaterfallFlow
//
//  Created by 许卫星 on 16/12/14.
//  Copyright © 2016年 许卫星. All rights reserved.
//

#import "ViewController.h"
#import "XWXWaterfallFlowLayout.h"
#import "XWXShop.h"
#import "XWXShopCell.h"
#import "MJExtension.h"

static NSString * const kIdentifier = @"shopIdentifier";

@interface ViewController ()<UICollectionViewDataSource,XWXWaterfallFlowLayoutDelegate>
/**商品信息**/
@property (nonatomic, strong) NSMutableArray *shops;
@property (nonatomic, weak) UICollectionView *collectionView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //1.布局界面
    [self setUpLayout];
    
    //2.获取数据
    [self loadFlowData];
}

- (void)setUpLayout
{
    //1.创建布局
    XWXWaterfallFlowLayout *flowLayout = [[XWXWaterfallFlowLayout alloc] init];
    flowLayout.delegate = self;
    
    //2.创建UICollectionView
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    [self.view addSubview:collectionView];
    collectionView.dataSource = self;
    collectionView.backgroundColor = [UIColor whiteColor];
    
    self.collectionView = collectionView;
    [self.collectionView registerClass:[XWXShopCell class] forCellWithReuseIdentifier:kIdentifier];
}

- (void)loadFlowData
{
    NSArray *shops = [XWXShop objectArrayWithFilename:@"1.plist"];
    [self.shops removeAllObjects];
    [self.shops addObjectsFromArray:shops];
    
    [self.collectionView reloadData];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.shops.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    XWXShopCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kIdentifier forIndexPath:indexPath];
    cell.shop = self.shops[indexPath.item];
    return cell;
}

#pragma mark - XWXWaterfallFlowLayoutDelegate
- (CGFloat)waterfallFlowLayout:(XWXWaterfallFlowLayout *)flowLayout itemIndexPatch:(NSIndexPath *)indexPatch itemW:(CGFloat)itemW
{
    XWXShop *shop = self.shops[indexPatch.item];
    CGFloat itemH = itemW * shop.h / shop.w;
    return itemH;
}

//列数
- (CGFloat)columnCountInWaterflowLayout:(XWXWaterfallFlowLayout *)waterflowLayout
{
    return 3;
}

//水平间隔
- (CGFloat)columnMarginInWaterflowLayout:(XWXWaterfallFlowLayout *)waterflowLayout
{
    return 10;
}

//垂直间隔
- (CGFloat)rowMarginInWaterflowLayout:(XWXWaterfallFlowLayout *)waterflowLayout
{
    return 10;
}

//四周间隔
- (UIEdgeInsets)edgeInsetsInWaterflowLayout:(XWXWaterfallFlowLayout *)waterflowLayout
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

#pragma mark - lazy
- (NSMutableArray *)shops
{
    if (_shops == nil) {
        _shops = [[NSMutableArray alloc] init];
    }
    return _shops;
}
@end
